package edu.xidian.sselab.cloudcourse.inputdata;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.client.Connection;
import org.apache.hadoop.hbase.client.ConnectionFactory;
import org.apache.hadoop.hbase.client.Table;
import java.io.IOException;

//连接Hbase数据库的工具类
public class HbaseClient {

    private Configuration configuration;//使用Configuration类实现信息配置
    private Connection connection;//Connection实现连接

    //
    public HbaseClient() {
        configuration = new Configuration();
        configuration.set("hbase.zookeeper.quorum", "wbj:2181,lh:2181");//配置zookeeper集群信息
    }

    public Connection getConnection() {
        if (connection == null || connection.isClosed()) {
            try {
                connection = ConnectionFactory.createConnection(configuration);//建立连接，类比MySql
            } catch (IOException e) {
                System.out.println("HBase数据库连接关闭，尝试重新连接失败!");
                e.printStackTrace();
            }
        }
        return connection;
    }

    public Table getTableByName(String tableName) {//通过Connection类实现对于特定表(table)的操作
        try {
            return connection.getTable(TableName.valueOf(tableName));
        } catch (IOException e) {
            System.out.println("连接数据库表失败!");
            e.printStackTrace();
        }
        return null;
    }
    public void closeConnection() { //用来关闭数据库连接
        if(connection != null && !connection.isClosed()) {
            try{
                connection.close();
            } catch (IOException e) {
                System.out.println("数据库连接关闭失败！");
                e.printStackTrace();
            }
        }
    }

}
